<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2020 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace app\admin\controller\wechatopen;

use app\admin\model\Admin;
use EasyWeChat\OpenPlatform\Application;
use EasyWeChat\OpenPlatform\Server\Guard;
use app\admin\model\wechatopen\Wechatopen;
use app\wechatopen\util\library\Mpopen;
use app\common\controller\Backend;
use app\wechatopen\controller\Authevent;
use EasyWeChat\Factory;
use fast\Random;
use think\Cache;
use think\Config;
use uctoo\ThinkEasyWeChat\Facade;
use think\Session;
use app\admin\model\wechatopen\AdminApplet;

/**
 * 微信应用信息管理
 *
 * @icon fa fa-circle-o
 */
class Applet extends Backend
{
    
    /**
     * Applet模型对象
     * @var \app\admin\model\wechatopen\Applet
     */
    protected $model = null;

    protected $dataLimit = 'auth';
    protected $multiFields = 'statue';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wechatopen\Applet;
        $this->view->assign("typedataList", $this->model->getTypedataList());
        $this->view->assign("statusList", $this->model->getStatusList());

	    $domainIP = gethostbyname($_SERVER['SERVER_NAME']);
        $this->view->assign("domainIP", $domainIP);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $admin_id = Session::get('admin_id');
        $auth_code = Session::get('auth_code');
        if(isset($admin_id) && isset($auth_code)){  //从微信第三方授权跳转回来的, 关联管理员帐号和APPID, 即使由于登录过期或用户关掉浏览器等原因无法授权后跳转回此页面, 在AuthorizedEventHandler里也会刷新授权信息,但可能出现应用未归属到对应商户帐号
            $wechatopenInfoConfig = Cache::get('wechatopen_config');
            $openPlatform = Facade::openPlatform($wechatopenInfoConfig['app_id'],$wechatopenInfoConfig);
            $auth = $openPlatform->handleAuthorize($auth_code);
            $appid = $auth['authorization_info']['authorizer_appid'];
            $app_info = $openPlatform->getAuthorizer($appid);

            $this->model->startTrans();
            $applet = $this->model->where('appid', $appid)->find();
            $db_data=[];
            if($applet){       //已存在appid帐号更新admin_id
                $db_data['wechatapplet_id'] = md5($appid);
                $db_data['admin_id'] = $admin_id;
                $db_data['name'] = $app_info['authorizer_info']['nick_name'];
                $db_data['principal'] = $app_info['authorizer_info']['principal_name'];
                $db_data['original'] = $app_info['authorizer_info']['user_name'];
                if (array_key_exists('head_img', $app_info['authorizer_info'])) {
                    $db_data['headface_image'] = $app_info['authorizer_info']['head_img'];
                }else{
                    $db_data['headface_image'] = '';
                }
                $db_data['qrcode_image'] = $app_info['authorizer_info']['qrcode_url'];
                $db_data['status'] = \app\admin\model\wechatopen\Applet::STATUS_AUTHORIZED;
                $db_data['service_type_info'] = json_encode($app_info['authorizer_info']['service_type_info']);
                $db_data['verify_type_info'] = json_encode($app_info['authorizer_info']['verify_type_info']);
                $db_data['business_info'] = json_encode($app_info['authorizer_info']['business_info']);
                $db_data['func_info'] = json_encode($app_info['authorization_info']['func_info']);
                $db_data['authorizer_access_token'] = $auth['authorization_info']['authorizer_access_token'];
                $db_data['access_token_overtime'] = time()+$auth['authorization_info']['expires_in']-1500;
                $db_data['authorizer_refresh_token'] = $auth['authorization_info']['authorizer_refresh_token'];
                if (array_key_exists('MiniProgramInfo', $app_info['authorizer_info'])) {   //是否是小程序授权
                    $db_data['miniprograminfo'] = json_encode($app_info['authorizer_info']['MiniProgramInfo']);
                    $db_data['signature'] = $app_info['authorizer_info']['signature'];
                    $db_data['typedata'] = 'miniapp';
                }else{
                    $db_data['wechat'] = $app_info['authorizer_info']['alias'];
                    if($db_data['service_type_info'] == 0 || $db_data['service_type_info'] == 1){
                        $db_data['typedata'] = 'serv_account';
                    }else{
                        $db_data['typedata'] = 'sub_account';
                    }
                }
                $result = $this->model->isUpdate(true)->where('appid',$appid)->update($db_data);
            }else{  //新增
                $app_info = $openPlatform->getAuthorizer($appid);
                $db_data['appid'] = $app_info['authorization_info']['authorizer_appid'];
                $db_data['wechatapplet_id'] = md5($appid);
                $db_data['admin_id'] = $admin_id;
                $db_data['name'] = $app_info['authorizer_info']['nick_name'];
                $db_data['principal'] = $app_info['authorizer_info']['principal_name'];
                $db_data['original'] = $app_info['authorizer_info']['user_name'];
                if (array_key_exists('head_img', $app_info['authorizer_info'])) {
                    $db_data['headface_image'] = $app_info['authorizer_info']['head_img'];
                }else{
                    $db_data['headface_image'] = '';
                }
                $db_data['qrcode_image'] = $app_info['authorizer_info']['qrcode_url'];
                $db_data['status'] = \app\admin\model\wechatopen\Applet::STATUS_AUTHORIZED;
                $db_data['service_type_info'] = json_encode($app_info['authorizer_info']['service_type_info']);
                $db_data['verify_type_info'] = json_encode($app_info['authorizer_info']['verify_type_info']);
                $db_data['business_info'] = json_encode($app_info['authorizer_info']['business_info']);
                $db_data['func_info'] = json_encode($app_info['authorization_info']['func_info']);
                $db_data['authorizer_access_token'] = $auth['authorization_info']['authorizer_access_token'];
                $db_data['access_token_overtime'] = time()+$auth['authorization_info']['expires_in']-1500;
                $db_data['authorizer_refresh_token'] = $auth['authorization_info']['authorizer_refresh_token'];
                if (array_key_exists('MiniProgramInfo', $app_info['authorizer_info'])) {   //是否是小程序授权
                    $db_data['miniprograminfo'] = json_encode($app_info['authorizer_info']['MiniProgramInfo']);
                    $db_data['signature'] = $app_info['authorizer_info']['signature'];
                    $db_data['typedata'] = 'miniapp';
                }else{
                    $db_data['wechat'] = $app_info['authorizer_info']['alias'];
                    if($db_data['service_type_info'] == 0 || $db_data['service_type_info'] == 1){
                        $db_data['typedata'] = 'serv_account';
                    }else{
                        $db_data['typedata'] = 'sub_account';
                    }
                }
                $result = $this->model->isUpdate(false)->save($db_data);
            }
            if($result === false){
                $this->model->rollBack();
                $this->error('添加失败');
            }
            // 提交事务
            $this->model->commit();
            //设置为管理员当前选中的applet
            AdminApplet::selectApplet($admin_id,$db_data['wechatapplet_id']);
            $applet = $this->model->where('appid', $appid)->find();  //刷新信息后的applet
            session('applet_info', $applet);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','wechatapplet_id','name','appid','mchid','status']);
                $row->visible(['admin']);
				$row->getRelation('admin')->visible(['username']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 切换应用
     */
    public function set_applet($ids = "")
    {
        if ($ids)
        {
            if(count($ids) > 1){
                $this->error('只能选择一个应用进行切换！');
            }
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $applet = $this->model->where($pk, 'in', $ids)->find();
            //设置为管理员当前选中的applet
            if($applet){
                AdminApplet::selectApplet($this->auth->id,$applet['wechatapplet_id']);
                // 缓存当前应用信息到session
                session('applet_info', $applet);
                $this->success('切换应用成功','index');
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
